package com.crawler.waf.serializer;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;

/**
 * 日期自定义格式化
 * @author rubekid
 *
 * 2017年2月18日 下午10:43:07
 */
public class CustomDateSerializer extends JsonSerializer<Date> { 
	
	private Logger logger = LoggerFactory.getLogger(getClass());
	  
	@Override
	public void serialize(Date value, JsonGenerator gen, SerializerProvider serializers)
			throws IOException, JsonProcessingException {
		gen.writeString(toString(value));
	}  
	
	/**
	 * 转成字符串
	 * @param date
	 * @return
	 */
	private String toString(Date date){
		Date now = new Date();
		long diff = (long) (Math.floor((now.getTime() - date.getTime()) / (60 * 1000)));
		if(diff < 1){
			return "刚刚";
		}
		else if(diff < 60){
			return diff + "分钟前";
		}
		else if(diff < 24 *60){
			int hours = (int) Math.floor(diff / 60);
			return hours + "小时前";
		}
		if(isSameYear(date, now)){
			return toString(date, "MM-dd HH:mm");
		}
		return toString(date, "yy-MM-dd HH:mm");
	}
	
	/**
	 * 以指定的格式来格式化日期
	 * 
	 * @param date Date
	 * @param format String
	 * @return String
	 */
	private String toString(Date date, String format) {
		String result = "";
		if (date != null) {
			try {
				SimpleDateFormat sdf = new SimpleDateFormat(format);
				result = sdf.format(date);
			} catch (Exception ex) {
				logger.error(ex.getMessage(), ex);
			}
		}
		return result;
	}
	
	/**
	 * 是否同一年
	 * @param src
	 * @param dest
	 * @return
	 */
	private boolean isSameYear(Date src, Date dest){
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(src);
		int srcYear = calendar.get(Calendar.YEAR);
		calendar.setTime(dest);
		int destYear = calendar.get(Calendar.YEAR);
		return srcYear == destYear;
	}
}  